package com.decard.baselibrarydemo.ui.fragment;

import android.os.Build;
import android.os.Bundle;

import androidx.appcompat.widget.AppCompatSpinner;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.decard.NDKMethod.BasicOper;
import com.decard.baselibrarydemo.R;
import com.decard.baselibrarydemo.model.DeviceModel;
import com.decard.baselibrarydemo.utils.TypesetRadioGroup;
import com.decard.baselibrarydemo.adapter.GalleryAdapter;
import com.decard.baselibrarydemo.adapter.MDSEUtils;
import com.decard.baselibrarydemo.adapter.PagingScrollHelper;
import com.decard.baselibrarydemo.adapter.PieceDataAdapter;
import com.decard.baselibrarydemo.adapter.TestArrayAdapter;
import com.decard.baselibrarydemo.utils.SPUtils;
import com.decard.baselibrarydemo.adapter.SectorDataBean;
import com.decard.baselibrarydemo.lister.M1CardListener;
import com.decard.baselibrarydemo.model.M1CardModel;
import com.decard.baselibrarydemo.utils.ConstUtils;
import com.decard.baselibrarydemo.utils.SnackbarUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class M1CardFragment extends Fragment implements GalleryAdapter.OnGalleryListener, PagingScrollHelper.onPageChangeListener, M1CardListener,View.OnClickListener {

    private RecyclerView rvSectors;

    private RecyclerView rvPieceData;

    private GalleryAdapter galleryAdapter;

    private PieceDataAdapter pieceDataAdapter;

    private LinearLayoutManager sectorsLm;

    TypesetRadioGroup trgType;

    private boolean keyTypeFlag = true;

    private SPUtils spUtils;

    private HashMap<String, String> sectrsKeyMap;

    private String[] sectorsNums;

    private int spinnerPosition;

//    private Button mDownload;

    private TextView etDownload;

    private Button mReadCard;

    private Button mClatCard;

    private RadioButton radioButton;

    private M1CardModel model;

    private ImageView mReturn;

    private ArrayAdapter<String> mAdapter ;

    private String [] mStringArray;

    private int port;


    private List<SectorDataBean> sectorDataBeanList;

//    AppCompatSpinner spinnerSectors;

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root= inflater.inflate(R.layout.fragment_m1_card, container, false);

        init(root);
        initview(root);
        setSectorsPiece();
        return root;
    }

    private void init(View root){
//        spinnerSectors=root.findViewById(R.id.spinner_sectors);
        mStringArray=getResources().getStringArray(R.array.sectorsNum);

        //使用自定义的ArrayAdapter
        mAdapter = new TestArrayAdapter(getContext(),mStringArray);

        //设置下拉列表风格(这句不些也行)
        //mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        spinnerSectors.setAdapter(mAdapter);
        //监听Item选中事件
//        spinnerSectors.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) new ItemSelectedListenerImpl());

    }

    private class ItemSelectedListenerImpl implements AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3) {
            System.out.println("选中了:"+mStringArray[position]);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

    }

    private void readSectorData(int currentSectors) {
        Log.e("TAG", "readSectorData: currentSectors=="+currentSectors );
        int piece = (currentSectors + 1) * 4;
        SectorDataBean sectorDataBean = new SectorDataBean();
        String[] pieceDatas = new String[4];
        for (int i = piece - 4, j = 0; i < piece; i++, j++) {
            String pieceData = MDSEUtils.returnResult(BasicOper.dc_read_hex(i));
            pieceDatas[j] = pieceData;
        }

        sectorDataBean.pieceZero = pieceDatas[0];
        sectorDataBean.pieceOne = pieceDatas[1];
        sectorDataBean.pieceTwo = pieceDatas[2];
        sectorDataBean.pieceThree = pieceDatas[3];
        updataSectorData(currentSectors, sectorDataBean);
    }
    private void initview(View root){

        radioButton=root.findViewById(R.id.rb_main_m1);
        radioButton.setChecked(true);

        rvSectors=root.findViewById(R.id.rv_sectors);

        rvPieceData=root.findViewById(R.id.rv_piece_data);

//        spinnerSectors=root.findViewById(R.id.spinner_sectors);

        //下载
//        mDownload=root.findViewById(R.id.btn_restoration_m1);
        //FFFFFF
        etDownload=root.findViewById(R.id.et_download_m1);

        //读卡
        mReadCard=root.findViewById(R.id.read_card_m1);

        //清卡
        mClatCard=root.findViewById(R.id.clear_btn_m1);

        //返回
        mReturn=root.findViewById(R.id.btn_return_key_m1);

//        mDownload.setOnClickListener(this);
        mReadCard.setOnClickListener(this);
        mClatCard.setOnClickListener(this);

        model = new M1CardModel(this);
        trgType=root.findViewById(R.id.rg_parent_m1);
        trgType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_main_m1:
                        keyTypeFlag = true;
                        break;
                    case R.id.rb_main_two_m1:
                        keyTypeFlag = false;
                        break;
                }
            }
        });



        spUtils = new SPUtils(getContext(),"sectorsKey");
        sectrsKeyMap = new HashMap<>();

        sectorsNums = getResources().getStringArray(R.array.sectorsNum);
        for (String sectorsNum : sectorsNums) {
            String passwordKey = spUtils.getString(sectorsNum, "FFFFFFFFFFFF");
            sectrsKeyMap.put(sectorsNum, passwordKey);
        }

//        spinnerSectors.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                spinnerPosition = position;
//                String passwordKey = sectrsKeyMap.get(sectorsNums[position]);
//                etDownload.setText(passwordKey);
//            }
//
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });

        mReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Navigation.findNavController(view).popBackStack();
            }
        });


    }



    @Override
    public void onClick(View view) {
        final int keyType = keyTypeFlag ? 0 : 4;
        switch (view.getId()){

//            case R.id.btn_restoration_m1:
                /* case R.id.btn_restoration_m1:*/

//                String newPasswordKey = etDownload.getText().toString();
//                if (!TextUtils.isEmpty(newPasswordKey) && newPasswordKey.length() == 12) {
//                    spUtils.put(sectorsNums[spinnerPosition], newPasswordKey);
//                    sectrsKeyMap.put(sectorsNums[spinnerPosition], newPasswordKey);
//                    String result = null;
//                    String[] resultArr = null;
//                    result = BasicOper.dc_load_key_hex(keyType,spinnerPosition,newPasswordKey);
//                    resultArr = result.split("\\|",-1);
//                    if(resultArr[0].equals("0000")){
//                        Log.d("dc_load_key_hex","success");
//                        Toast.makeText(getContext(), "下载成功", Toast.LENGTH_SHORT).show();
//                    }else{
//                        Log.d("dc_load_key_hex","error code = "+resultArr[0] +" error msg = "+resultArr[1] );
//                        Toast.makeText(getContext(), "下载失败", Toast.LENGTH_SHORT).show();
//                    }
//                }

//                break;

            case R.id.read_card_m1:
                String result = BasicOper.dc_card_n_hex(0);

                if (!MDSEUtils.isSucceed(result)) {
                    Toast.makeText(getContext(), "m1卡不存在", Toast.LENGTH_SHORT).show();
                    SnackbarUtils.showShortSnackbar(getActivity(), result);
                    return;
                }

                int firstVisibleItemPosition = sectorsLm.findFirstVisibleItemPosition();
                model.bt_read_card(ConstUtils.BT_READ_CARD,keyType,firstVisibleItemPosition);

                break;

            case R.id.clear_btn_m1:
                initSectorData();
                SnackbarUtils.showShortSnackbar(getActivity(), getString(R.string.clean_succeed));

          /*      String result = null;
                String[] resultArr = null;
                result = BasicOper.dc_halt();
                resultArr = result.split("\\|",-1);
                if(resultArr[0].equals("0000")){
                    Log.d("dc_halt","success");
                }else{
                    Log.d("dc_halt","error code = "+resultArr[0] +" error msg = "+resultArr[1] );
                }*/
                break;
        }
    }

    private void setSectorsPiece() {
        /* String[] sectorsNum = new String[51];*/
        String[] sectorsNum = new String[33];
//        for (int i = -1; i < 50; i++) {
        for (int i = -1; i < 32; i++) {
            if (i == -1) {
                sectorsNum[0] = "All";
            } else if (i < 16) {
                sectorsNum[i + 1] = i + "";
            } else {
                sectorsNum[i + 1] = "";
            }
        }

        sectorsLm = new LinearLayoutManager(getContext());
        sectorsLm.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvSectors.setLayoutManager(sectorsLm);
        galleryAdapter = new GalleryAdapter(getContext(), sectorsNum);
        galleryAdapter.setOnGalleryListener(this);
        rvSectors.setAdapter(galleryAdapter);


        LinearLayoutManager pieceDataLm = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        PagingScrollHelper scrollHelper = new PagingScrollHelper();
        pieceDataAdapter = new PieceDataAdapter(getContext());
        rvPieceData.setLayoutManager(pieceDataLm);
        rvPieceData.setAdapter(pieceDataAdapter);
        scrollHelper.setUpRecycleView(rvPieceData);
        scrollHelper.setOnPageChangeListener(this);
        scrollHelper.updateLayoutManger();
        initSectorData();
    }
    private void initSectorData() {

        sectorDataBeanList = new ArrayList<>();
        sectorDataBeanList.clear();
        for (int i = 0; i < 16; i++) {
            SectorDataBean sectorDataBean = new SectorDataBean();
            sectorDataBean.pieceZero = "   " ;
            sectorDataBean.pieceOne = "    " ;
            sectorDataBean.pieceTwo = "    " ;
            sectorDataBean.pieceThree = "   " ;
            sectorDataBeanList.add(sectorDataBean);
        }
        updataSectorData(sectorDataBeanList);
    }
    private void updataSectorData(List<SectorDataBean> sectorDataBeenList) {
        pieceDataAdapter.setPieceData(sectorDataBeenList);
    }

    private void updataSectorData(int postion, SectorDataBean sectorDataBean) {
        sectorDataBeanList.set(postion, sectorDataBean);
        updataSectorData(sectorDataBeanList);
    }

    @Override
    public void itemClick(View view, int postion) {
        sectorsLm.scrollToPositionWithOffset(postion, 0);
        sectorsLm.setStackFromEnd(false);
        if (postion == 1 || postion == 0) {
            rvPieceData.smoothScrollToPosition(0);
        } else {
            rvPieceData.smoothScrollToPosition(postion - 1);
        }
    }

    @Override
    public void onPageChange(int index) {
        int currentPostion;
        if (index == 0) {
            currentPostion = 1;
            sectorsLm.scrollToPositionWithOffset(currentPostion, 0);
        } else {
            currentPostion = index + 1;
            sectorsLm.scrollToPositionWithOffset(currentPostion, 0);
        }
        galleryAdapter.setSelectItem(currentPostion);
    }

    @Override
    public void getM1CardResult(String cmd, List<String> list, String result, String result_) {
        switch (cmd){
            case ConstUtils.BT_DOWNLOAD:
                if (list == null){
                    SnackbarUtils.showShortSnackbar(getActivity(),
                            MDSEUtils.isSucceed(result) ? getString(R.string.keyDownloadSucceed) : getString(R.string.keyDownloadFail));
                }else {
                    SnackbarUtils.showShortSnackbar(getActivity(), ! list.isEmpty() ?
                            list + getString(R.string.sectors) + " " + getString(R.string.keyDownloadFail) : getString(R.string.allDownloadSucceed));
                }
                break;

            case ConstUtils.BT_READ_CARD:
                if (list == null){
                    if (result.length() > 2){
                        boolean b;
                        if ("true".equals(result)){
                            b = true;
                        }else {
                            b = false;
                        }
                        Log.d("tag","result:" + result);
                        SnackbarUtils.showShortSnackbar(getActivity(), b ?
                                getString(R.string.sectors) + " " + Integer.parseInt(result_) + getString(R.string.authSucceed) :
                                getString(R.string.sectors) + " " + Integer.parseInt(result_) + getString(R.string.authFail));
                        readSectorData(Integer.parseInt(result_));
                    }else {
                        readSectorData(Integer.parseInt(result));
                    }
                }else {
                    SnackbarUtils.showShortSnackbar(getActivity(), !list.isEmpty() ?
                            list + getString(R.string.sectors) + " " + getString(R.string.authFail) : getString(R.string.allAuthSucceed));
                }
                break;
        }
    }
}
